package com.my.socket.bio.v1;

import com.my.socket.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by ZhongGang
 * at 2018/6/27 9:47
 */
public class ReverseServer {
    private static final Logger LOGGER = LoggerFactory.getLogger(ReverseServer.class);

    public static void main(String[] args) throws Exception {
        int count = 0;
        ServerSocket serverSocket = new ServerSocket();
        serverSocket.bind(new InetSocketAddress("127.0.0.1", 9999));
        Socket socket;
        while ((socket = serverSocket.accept()) != null) {
            try {
                InputStream inputStream = socket.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                String line = reader.readLine();
                LOGGER.info("read line {} from client {}", line, socket);

                OutputStream outputStream = socket.getOutputStream();
                PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream));
                String reversedLine = StringUtils.reverse(line);
                writer.println(reversedLine);
                writer.flush();
                LOGGER.info("write reversed line {} to client {}", reversedLine, socket);
            } catch (Exception e) {
                LOGGER.error("exception caught, the error is {}", e.getMessage());
            } finally {
                count += 1;
                socket.close();
                LOGGER.info("total connections: {}", count);
            }
        }
    }
}
